package com.app.utils.spring.datasource;

import com.zaxxer.hikari.HikariConfig;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.env.Environment;

public class DataSourceConfigUtil {
    public static HikariConfig setDataSourceEnvConfig(String prefix1, String prefix, Environment env) {

        HikariConfig config = new HikariConfig();
        String driver=env.getProperty(prefix1 + "driver-class-name");
        String dataSourceUrl= env.getProperty(prefix1 + "jdbcUrl");
        String user=env.getProperty(prefix1 + "username");
        String password=env.getProperty(prefix1 + "password");
        String minimumIdle = env.getProperty(prefix + "minimumIdle");
        String maximumPoolSize = env.getProperty(prefix + "maximumPoolSize");
        String autoCommit = env.getProperty(prefix + "autoCommit");
        String idleTimeout = env.getProperty(prefix + "idleTimeout");
        String poolName = env.getProperty(prefix + "poolName");
        String maxLifetime = env.getProperty(prefix + "maxLifetime");
        String connectionTimeout = env.getProperty(prefix + "connectionTimeout");
        String dataSourceClassName= env.getProperty(prefix1+ "type");
        if (StringUtils.isNotBlank(dataSourceUrl)){
            config.setJdbcUrl(dataSourceUrl);
        }
        if (StringUtils.isNotBlank(user)){
            config.setUsername(user);
        }
        if (StringUtils.isNotBlank(password)){
            config.setPassword(password);
        }
        if (StringUtils.isNotBlank(driver)){
            config.setDriverClassName(driver);
        }

        if (StringUtils.isNotBlank(minimumIdle)){
            config.setMinimumIdle(Integer.parseInt(minimumIdle));
        }
        if (StringUtils.isNotBlank(maximumPoolSize)) {
            config.setMaximumPoolSize(Integer.parseInt(maximumPoolSize));
        }
        if (StringUtils.isNotBlank(autoCommit)) {
            config.setAutoCommit(Boolean.parseBoolean(autoCommit));
        }
        if (StringUtils.isNotBlank(idleTimeout)) {
            config.setIdleTimeout(Integer.parseInt(idleTimeout));
        }
        if (StringUtils.isNotBlank(poolName)){
            config.setPoolName(poolName);
        }
        if (StringUtils.isNotBlank(maxLifetime)) {
            config.setMaxLifetime(Integer.parseInt(maxLifetime));
        }
        if (StringUtils.isNotBlank(connectionTimeout)) {
            config.setConnectionTimeout(Integer.parseInt(connectionTimeout));
        }
        return config;
    }
}
